<template>
  <div class="time-mail-view">
    <div class="container">
      <h1 class="page-title">时空邮件</h1>
      <p class="page-subtitle">给未来的自己写一封信，约定一个开启日期</p>

      <!-- Mail Writing Section -->
      <section class="write-mail-section">
        <h2 class="section-title">写一封时空邮件</h2>
        <div class="mail-form">
          <div class="form-group">
            <label for="mail-title">标题:</label>
            <input type="text" id="mail-title" v-model="newMail.title">
          </div>
          <div class="form-group">
            <label for="mail-content">内容:</label>
            <textarea id="mail-content" v-model="newMail.content"></textarea>
          </div>
          <div class="form-group">
            <label for="open-date">开启日期:</label>
            <input type="date" id="open-date" v-model="newMail.openDate">
          </div>
          <button @click="saveMail">保存邮件</button>
        </div>
      </section>

      <!-- Mail Tree Visualization Section -->
      <section class="mail-tree-section">
        <h2 class="section-title">我的时空信件树</h2>
        <div class="tree-container" ref="treeContainer"></div>
      </section>

    </div>
    
    <!-- Mail Content Modal (Simplified for now) -->
    <div v-if="selectedMail" class="mail-modal-overlay" @click.self="closeMail">
        <div class="mail-modal-content">
            <h3>{{ selectedMail.title }}</h3>
            <p v-if="selectedMail.isOpened">{{ selectedMail.content }}</p>
            <p v-else>此信件尚未到开启日期。</p>
            <button @click="closeMail">关闭</button>
        </div>
    </div>

  </div>
</template>

<script>
import * as PIXI from 'pixi.js';

export default {
  name: 'TimeMailView',
  data() {
    return {
      newMail: {
        title: '',
        content: '',
        openDate: '',
      },
      mailList: [
        // Sample mail data with position (will be replaced with backend data)
        { id: 1, title: '致未来的我 (已开启)', content: '你好！希望你现在过得很好。这是写于 2024 年 5 月的信。', openDate: '2023-01-01', isOpened: true, position: { top: '35%', left: '45%' } },
        { id: 2, title: '未来的计划', content: '希望到 2025 年 6 月 1 日，你已经...', openDate: '2025-06-01', isOpened: false, position: { top: '40%', left: '55%' } },
        { id: 3, title: '给自己打气', content: '...', openDate: '2026-01-01', isOpened: false, position: { top: '25%', left: '40%' } },
        { id: 4, title: '一个秘密', content: '...', openDate: '2024-12-31', isOpened: true, position: { top: '25%', left: '60%' } },
      ],
      selectedMail: null, // To store the mail selected for viewing
      pixiApp: null, // PixiJS application instance
    };
  },
  methods: {
    saveMail() {
      // This method will eventually send data to the backend API
      console.log('Saving mail:', this.newMail);
      alert('邮件保存功能待实现，请查看控制台输出。');
      // Clear the form after attempting to save
      this.newMail = { title: '', content: '', openDate: '' };
    },
    async fetchMails() {
        // This method will eventually fetch mail data from the backend API
        console.log('Fetching mails...');
        // For now, use sample data
        // This.mailList will be populated here
        
        // After fetching, render with PixiJS
        // Use async/await with $nextTick
        await this.$nextTick();
        await this.renderTreeWithPixi();
    },
    openMail(mail) {
        // Check if the mail is opened based on openDate compared to current date
        const today = new Date();
        const openDate = new Date(mail.openDate);
        mail.isOpened = openDate <= today;
        
        this.selectedMail = mail;
    },
    closeMail() {
        this.selectedMail = null;
    },
    async renderTreeWithPixi() {
        // Placeholder for PixiJS rendering logic
        console.log('Rendering tree with PixiJS...', this.mailList);
        
        // Debugging logs
        console.log('treeContainer ref:', this.$refs.treeContainer);
        if (this.$refs.treeContainer) {
            console.log('treeContainer dimensions:', this.$refs.treeContainer.clientWidth, 'x', this.$refs.treeContainer.clientHeight);
        }

        if (!this.pixiApp) {
            console.log('Initializing PixiJS App instance...');
            // Create PixiJS App instance (constructor does not take options in v8+)
            this.pixiApp = new PIXI.Application(); 
            
            console.log('Calling pixiApp.init() with options...');
            // Call the async init method on the instance
            await this.pixiApp.init({
                width: this.$refs.treeContainer.clientWidth,
                height: this.$refs.treeContainer.clientHeight,
                backgroundColor: 0x0d1117, // Match background color
                resolution: window.devicePixelRatio || 1,
                autoDensity: true,
            });
            
            console.log('PixiJS App initialized and configured:', this.pixiApp);
            
            // Add the canvas to the container
            if (this.$refs.treeContainer) {
                this.$refs.treeContainer.appendChild(this.pixiApp.canvas); 
                console.log('PixiJS canvas appended to container.'); 
            } else {
                console.error('Error: treeContainer ref is null when trying to append PixiJS canvas.'); 
            }
            
            // Handle window resizing
            window.addEventListener('resize', this.handleResize);
        } else {
            console.log('PixiJS App already initialized.');
        }
        
        // Clear previous content
        this.pixiApp.stage.removeChildren();
        
        // *** PixiJS Drawing Logic Goes Here ***
        
        // Draw Tree (Simplified)
        const treeGraphics = new PIXI.Graphics();

        // Draw Trunk (using new v8+ Graphics API)
        treeGraphics
            .rect(this.pixiApp.screen.width / 2 - 20, this.pixiApp.screen.height - 200, 40, 200) // Use rect instead of drawRect
            .fill(0x8B4513); // Use fill instead of beginFill/endFill

        // Draw Branches (simplified, using new v8+ Graphics API)
        treeGraphics
            .rect(this.pixiApp.screen.width / 2 - 100, this.pixiApp.screen.height - 250, 100, 20)
            .rect(this.pixiApp.screen.width / 2 + 0, this.pixiApp.screen.height - 250, 100, 20)
            .fill(0x8B4513);

        // Draw Leaves (simplified circles, using new v8+ Graphics API)
        treeGraphics
            .circle(this.pixiApp.screen.width / 2, this.pixiApp.screen.height - 300, 80)
            .circle(this.pixiApp.screen.width / 2 - 80, this.pixiApp.screen.height - 280, 60)
            .circle(this.pixiApp.screen.width / 2 + 80, this.pixiApp.screen.height - 280, 60)
            .fill(0x2E8B57);

        this.pixiApp.stage.addChild(treeGraphics);

        // Draw envelopes
        this.mailList.forEach(mail => {
            // Create a container for the envelope and text
            const mailContainer = new PIXI.Container();

            const envelopeGraphic = new PIXI.Graphics();
            envelopeGraphic
                .rect(0, 0, 40, 30) // Envelope size, position relative to container (0,0)
                .fill(0xe74c3c); // Red color

            // Optional: Add text for date on envelope (using new v8+ Text API)
            const dateText = new PIXI.Text({
                text: mail.openDate,
                style: {
                    fontFamily: 'Arial',
                    fontSize: 12,
                    fill: '#FFFFFF', // Use CSS string format for fill
                    align: 'center',
                }
            });
            // Position text relative to the top-left of the container (which is also the top-left of the envelopeGraphic for now)
            dateText.x = envelopeGraphic.width / 2;
            dateText.y = envelopeGraphic.height / 2;
            dateText.anchor.set(0.5); // Center the text anchor
            
            // Add graphic and text to the container
            mailContainer.addChild(envelopeGraphic);
            mailContainer.addChild(dateText);

            // Calculate pixel position for the container from percentage
            const containerWidth = this.pixiApp.screen.width;
            const containerHeight = this.pixiApp.screen.height;
            
            const topPercent = parseFloat(mail.position.top) / 100;
            const leftPercent = parseFloat(mail.position.left) / 100;

            mailContainer.x = containerWidth * leftPercent; 
            mailContainer.y = containerHeight * topPercent; 

            // Adjust container pivot to center the combined envelope+text at the calculated position
            mailContainer.pivot.set(mailContainer.width / 2, mailContainer.height / 2);
            
            mailContainer.interactive = true;
            mailContainer.buttonMode = true;
            // Use pointertap for click-like behavior in PixiJS
            mailContainer.on('pointertap', () => this.openMail(mail));
            
            this.pixiApp.stage.addChild(mailContainer);
        });
    },
    handleResize() {
        if (this.pixiApp && this.$refs.treeContainer) {
            this.pixiApp.renderer.resize(this.$refs.treeContainer.clientWidth, this.$refs.treeContainer.clientHeight);
            // Redraw content if necessary based on new size
            // await this.renderTreeWithPixi(); // May need adjustments to avoid re-initializing app, also needs to be async
        }
    }
  },
  async mounted() {
    this.fetchMails();
  },
  beforeDestroy() {
      if (this.pixiApp) {
          this.pixiApp.destroy(true);
          window.removeEventListener('resize', this.handleResize);
      }
  }
};
</script>

<style scoped>
.time-mail-view {
  padding: 80px 0;
  background: linear-gradient(135deg, #0d1117 0%, #161b22 100%);
  color: #c9d1d9;
  min-height: 100vh;
  overflow-x: hidden; /* Prevent horizontal scroll */
}

.container {
  max-width: 1000px; /* Adjust max-width for tree visualization */
  width: 100%;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  text-align: center;
  font-size: 2.8rem;
  background: linear-gradient(90deg, #58a6ff, #8b949e);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  margin-bottom: 0.5rem;
  letter-spacing: -0.5px;
}

.page-subtitle {
    text-align: center;
    font-size: 1.2rem;
    color: #8b949e;
    margin-bottom: 4rem;
}

.section-title {
  font-size: 2rem;
  color: #c9d1d9;
  margin-bottom: 1.5rem;
  text-align: center;
}

.write-mail-section {
    margin-bottom: 4rem;
    padding: 2rem;
    background: rgba(13, 17, 23, 0.7);
    border: 1px solid #30363d;
    border-radius: 12px;
    backdrop-filter: blur(10px);
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.mail-form .form-group {
    margin-bottom: 1.5rem;
}

.mail-form label {
    display: block;
    font-size: 1.1rem;
    color: #c9d1d9;
    margin-bottom: 0.5rem;
}

.mail-form input[type="text"],
.mail-form textarea,
.mail-form input[type="date"] {
    width: 100%;
    padding: 0.8rem;
    border: 1px solid #30363d;
    border-radius: 6px;
    background-color: #0d1117;
    color: #c9d1d9;
    font-size: 1rem;
    box-sizing: border-box;
}

.mail-form textarea {
    min-height: 150px;
    resize: vertical;
}

.mail-form input[type="date"]::-webkit-calendar-picker-indicator {
    filter: invert(80%);
}

.mail-form button {
    display: block;
    width: 100%;
    padding: 1rem;
    background-color: #238636;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 1.2rem;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.mail-form button:hover {
    background-color: #2ea043;
}

.mail-tree-section {
    margin-bottom: 4rem;
}

.mail-tree-section .section-title {
    margin-bottom: 3rem;
}

.tree-container {
    position: relative;
    width: 100%;
    height: 600px; /* Adjust height as needed */
    margin: 0 auto;
    /* Removed flex properties */
    /* Removed overflow */
}

/* Remove all CSS tree styles */
/*
.tree {
    ...
}

.trunk {
    ...
}

.branches {
    ...
}

.branch {
    ...
}

.branch-1 {
    ...
}

.branch-2 {
    ...
}

.branch-3 {
    ...
}

.branch-4 {
    ...
}

.leaves {
    ...
}

.leaf-group {
    ...
}

.leaf-group-1 {
    ...
}

.leaf-group-2 {
    ...
}

.leaf-group-3 {
    ...
}
*/

/* Remove CSS envelope styles */
/*
.envelope {
    ...
}

.envelope:hover {
    ...
}

.envelope i {
    ...
}

.envelope-date {
    ...
}
*/

/* Styles for Mail Content Modal */
.mail-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.mail-modal-content {
    background: #0d1117;
    border: 1px solid #30363d;
    border-radius: 12px;
    padding: 2rem;
    max-width: 600px;
    width: 90%;
    color: #c9d1d9;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.5);
}

.mail-modal-content h3 {
    font-size: 1.8rem;
    color: #58a6ff;
    margin-top: 0;
    margin-bottom: 1.5rem;
}

.mail-modal-content p {
    font-size: 1.1rem;
    line-height: 1.6;
    margin-bottom: 1.5rem;
}

.mail-modal-content button {
    display: block;
    width: 100px;
    margin: 0 auto;
    padding: 0.8rem 1.5rem;
    background-color: #30363d; /* Dark grey button */
    color: #c9d1d9;
    border: none;
    border-radius: 6px;
    font-size: 1rem;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.mail-modal-content button:hover {
    background-color: #444c56;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .time-mail-view {
    padding: 40px 0;
  }

  .container {
      padding: 0 15px;
  }

  .page-title {
    font-size: 2.2rem;
  }

  .page-subtitle {
      font-size: 1rem;
      margin-bottom: 3rem;
  }

  .section-title {
    font-size: 1.8rem;
  }

  .write-mail-section,
  .mail-tree-section {
      padding: 1.5rem;
  }

  .mail-form label {
      font-size: 1rem;
  }

  .mail-form input[type="text"],
  .mail-form textarea,
  .mail-form input[type="date"] {
      font-size: 0.9rem;
  }

  .mail-form button {
      font-size: 1rem;
      padding: 0.8rem;
  }

  .tree-container {
      height: 400px; /* Adjust height for smaller screens */
  }

  .envelope {
      width: 30px; /* Adjust size */
      height: 20px; /* Adjust size */
      padding: 3px;
  }

  .envelope i {
      font-size: 0.9rem;
  }

  .envelope-date {
      font-size: 0.6rem;
  }

   .mail-modal-content {
       padding: 1.5rem;
   }

   .mail-modal-content h3 {
       font-size: 1.5rem;
   }

   .mail-modal-content p {
       font-size: 1rem;
   }
}
</style> 